package cn.com.sbell.vss;

import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import org.apache.commons.httpclient.NameValuePair;

import cn.com.sbell.vss.csg.vsclient.util.CSGConfiguration;
import cn.com.sbell.vss.util.VssValidator;

/**
 * Tool class
 * 
 * @author Yifu.HUANG
 */
public class Util { //extends Network {

	private static final Log log = LogFactory.getLog(Util.class);

	public static void setParameter(Map map, String tagName, String mapKey,
			Object faultValue, HttpServletRequest request) {
		String object = request.getParameter(tagName);
		if ((object == null) || (object.equals(faultValue))) {
			return;
		}

		map.put(mapKey, object);
	}

//	public static void checkServerPermission(
//			AreaPermissionChecker areaPermissionChecker, VissServer server,
//			HttpServletRequest request) {
//
//		if (server == null || (Util.strIsNull(server.getAreaId()))) {
//			areaPermissionChecker.check(VssConstants.ROOT_AREA_ID, request);
//		} else {
//			areaPermissionChecker.check(server.getAreaId(), request);
//		}
//	}

	/**
	 * NOT complete yet!!!
	 */
	public static String[] splitByCommaWithoutDuplicate(String str) {
		String[] s = splitByComma(str);
		List list = new ArrayList();
		for (int i = 0; i < s.length; i++) {
			if (list.contains(s[i])) {
				continue;
			}
			list.add(s[i]);
		}
		String[] ret = new String[list.size()];
		list.toArray(ret);
		return ret;
	}

	public static String[] duplicate(String[] str) {
		Set set = new HashSet(Arrays.asList(str));
		return (String[]) set.toArray(new String[0]);
	}

	public static String[] splitByComma(String str) {
		return splitBy(str, ',');
	}

	public static String[] splitBy(String str, char sp) {
		if (str == null) {
			return new String[0];
		}
		str = str.trim();
		if (str.equals("")) {
			return new String[0];
		}
		List list = new ArrayList();
		StringBuffer sb = new StringBuffer();
		boolean inQuote = false;

		int len = str.length();
		for (int i = 0; i < len; i++) {
			char ch = str.charAt(i);
			if (ch == '\\' && (i + 1) < len) { // \?
				++i;
				ch = str.charAt(i);
				sb.append(ch);
				continue;
			} else if ((sb.length() == 0)
					&& (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n')) {
				continue;
			} else if (i + 1 == len) {
				if (ch == '"' && inQuote) {
					inQuote = false;
					String s = sb.toString().trim();
					sb.delete(0, sb.length());
					list.add(s);
				} else if (ch != sp) {
					sb.append(ch);
					String s = sb.toString().trim();
					sb.delete(0, sb.length());
					list.add(s);
				} else {
					String s = sb.toString().trim();
					sb.delete(0, sb.length());
					list.add(s);
					list.add("");
				}
				break;
			} else if (ch == sp && !inQuote) {
				String s = sb.toString().trim();
				sb.delete(0, sb.length());
				list.add(s);
				continue;
			}

			if (ch == '\"' && sb.length() == 0 && str.indexOf('\"', i + 1) > 0) { // "
				inQuote = true;
			} else if (ch == '\"' && inQuote) { // "
				inQuote = false;
			} else {
				sb.append(ch);
			}
		}

		String[] ret = new String[list.size()];
		list.toArray(ret);
		return ret;
	}

	public static void setParameter(Map map, String tagName, Object faultValue,
			HttpServletRequest request) {
		setParameter(map, tagName, tagName, faultValue, request);
	}

	public static boolean strIsNull(String str) {
		return ((str == null) || "".equals(str));
	}

	/**
	 * check if List list is null
	 * 
	 * @param list
	 *            List
	 * @return boolean
	 */
	public static boolean listIsNull(List list) {
		if (list != null && !list.isEmpty() && list.get(0) != null) {
			return false;
		} else {
			return true;
		}
	}

	public static boolean arrayIsNull(Object[] aObj) {
		if (aObj != null && aObj.length > 0) {
			for (int i = 0; i < aObj.length; i++) {
				if (aObj[i] != null && !"".equals(aObj[i])) {
					return false;
				}
			}
		}
		return true;
	}

	public static String getTrimParameter(HttpServletRequest request,
			String name) {
		String value = request.getParameter(name);
		if (value == null) {
			return "";
		} else {
			return value.trim();
		}
	}

	public static String getStringParameter(HttpServletRequest request,
			String name, boolean required, int maxLength, String fieldLabel) {
		String value = getTrimParameter(request, name);
		if (required && value.length() == 0) {
			throw new VssException(VssConstants.CODE_REQUIRED, fieldLabel);
		}
		if (maxLength != -1) {
			VssValidator.validateMaxLength(fieldLabel, value, required,
					maxLength);
		}
		return value;
	}

	public static boolean getBooleanParameter(HttpServletRequest request,
			String name) {
		String value = getTrimParameter(request, name);
		return Boolean.valueOf(value).booleanValue();
	}

	public static int getIntParameter(HttpServletRequest request, String name,
			boolean required, String fieldLabel, int defaultValue) {
		try {
			return getIntParameter(request, name, required, fieldLabel);
		} catch (Exception ex) {
			return defaultValue;
		}
	}

	public static int getIntParameter(HttpServletRequest request, String name,
			boolean required, String fieldLabel) {
		String value = getTrimParameter(request, name);
		if (required && value.length() == 0) {
			throw new VssException(VssConstants.CODE_REQUIRED, fieldLabel);
		}
		VssValidator.validateNumber(fieldLabel, value, required,
				VssConstants.DATA_INTEGER);
		return Integer.parseInt(value, 10);
	}

	public static int[] getIntParameters(HttpServletRequest request,
			String name, boolean required, String fieldLabel) {
		String[] value = request.getParameterValues(name);
		if (required && (value == null || value.length == 0)) {
			throw new VssException(VssConstants.CODE_REQUIRED, fieldLabel);
		}
		int values[] = new int[value.length];
		for (int i = 0; i < value.length; i++) {
			VssValidator.validateNumber(fieldLabel, value[i], required,
					VssConstants.DATA_INTEGER);
			values[i] = Integer.parseInt(value[i], 10);
		}
		return values;
	}

	public static void populate(HttpServletRequest request, Object dest,
			String paramName, String propertyName, boolean ignoreEmptyString) {
		String value = request.getParameter(paramName);
		if (dest == null
				|| (ignoreEmptyString && (value == null || value.trim()
						.length() == 0))) {
			log.debug("No property to populate");
			return;
		}
		setProperty(dest, propertyName, value);
	}

	public static void populate(HttpServletRequest request, Object dest,
			boolean ignoreEmptyString) {
		Enumeration en = request.getParameterNames();
		if (en == null || dest == null) {
			log.debug("No property to populate");
			return;
		}
		while (en.hasMoreElements()) {
			String name = (String) en.nextElement();
			String value = request.getParameter(name);
			if (ignoreEmptyString && (value == null || value.trim().equals(""))) {
				if (log.isDebugEnabled()) {
					log.debug("Property " + name + " is empty, ignore it");
				}
				continue;
			} else {
				value = toTrimmedString(value);
				setProperty(dest, name, value);
			}
		}
	}

	public static void setProperty(Object dest, String propertyName,
			String value) {
		if (log.isDebugEnabled()) {
			log.debug("Setting property " + propertyName + " = " + value);
		}

		if (dest instanceof Map) {
			((Map) dest).put(propertyName, value);
			log.debug("Property was set");
			return;
		}

		String setterMethodName = "set"
				+ propertyName.substring(0, 1).toUpperCase()
				+ propertyName.substring(1);

		try {
			Method m = dest.getClass().getMethod(setterMethodName,
					new Class[] { String.class });
			if (m != null) {
				try {
					m.invoke(dest, new Object[] { value });
					log.debug("Property was set");
					return;
				} catch (IllegalArgumentException ex) {
					log.debug("IllegalArgumentException", ex);
				} catch (IllegalAccessException ex) {
					log.debug("IllegalAccessException", ex);
				} catch (InvocationTargetException ex) {
					log.debug("InvocationTargetException", ex);
				}
			}
		} catch (SecurityException ex) {
			// log.debug("SecurityException", ex);
		} catch (NoSuchMethodException ex) {
			// log.debug("NoSuchMethodException", ex);
		}

		Method[] methods = dest.getClass().getMethods();
		for (int i = 0; i < methods.length; i++) {
			if (methods[i].getName().equalsIgnoreCase(setterMethodName)) {
				Class[] types = methods[i].getParameterTypes();

				if (types.length == 1) {
					Object param = value;
					if (types[0].equals(String.class)) {
						;
					} else if (types[0] == Boolean.class
							|| types[0] == boolean.class) {
						param = Boolean.valueOf(value);
					} else if (types[0] == Float.class
							|| types[0] == float.class) {
						param = Float.valueOf(value);
					} else if (types[0] == Double.class
							|| types[0] == double.class) {
						param = Double.valueOf(value);
					} else if (types[0] == Integer.class
							|| types[0] == int.class) {
						param = Integer.valueOf(value);
					} else if (types[0] == Long.class || types[0] == long.class) {
						param = Long.valueOf(value);
					} else if (types[0] == (Date.class)) {
						if (validateLong(value)) {
							long millis = Long.parseLong(value);
							if (millis < 114812113977L) {
								millis = millis * 1000;
							}
							param = new Date(millis);
						} else {
							try {
								param = getDefaultDateFormat().parse(value);
							} catch (ParseException ex) {
								log.debug("Parse date format error: " + value);
							}
						}
					} else {
						log.debug("Unsupport property type: "
								+ types[0].getName());
						continue;
					}
					try {
						methods[i].invoke(dest, new Object[] { param });
						log.debug("Property was set");
						break;
					} catch (IllegalArgumentException ex) {
						log.debug("IllegalArgumentException", ex);
					} catch (IllegalAccessException ex) {
						log.debug("IllegalAccessException", ex);
					} catch (InvocationTargetException ex) {
						log.debug("InvocationTargetException", ex);
					}
				}
			}
		}
	}

	public static String getDomainId(HttpServletRequest request) {
		String domainId = request.getParameter("targetDomainId");
		if (strIsNull(domainId)) {
			VissSession session = (VissSession) request
					.getAttribute(VssConstants.KEY_USER_SESSION_DATA);
			domainId = session.getDomainId();
		}
		return domainId;
	}

	public static String getSessionId(HttpServletRequest request) {
		String sessionId = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if ("sessionId".equals(cookies[i].getName())) {
					sessionId = cookies[i].getValue();
					break;
				}
			}
		}
		if (sessionId == null) {
			sessionId = request.getParameter("sessionId");
		}
		if (sessionId != null) {
			sessionId = sessionId.trim();
		}
		return sessionId;
	}

	/**
	 * Checks if the field can safely be converted to an int primitive.
	 * 
	 * @param value
	 *            String
	 * @return boolean
	 */
	public static boolean validateInt(String value) {

		if (strIsNull(value)) {
			return false;
		}

		try {
			new Integer(value);
		} catch (NumberFormatException e) {
			return false;
		}

		return true;
	}

	/**
	 * Checks if the field can safely be converted to an double primitive.
	 * 
	 * @param value
	 *            String
	 * @return boolean
	 */
	public static boolean validateDouble(String value) {

		if (strIsNull(value)) {
			return false;
		}

		try {
			new Double(value);
		} catch (NumberFormatException e) {
			return false;
		}

		return true;
	}

	/**
	 * Checks if the field can safely be converted to an long primitive.
	 * 
	 * @param value
	 *            String
	 * @return boolean
	 */
	public static boolean validateLong(String value) {

		if (strIsNull(value)) {
			return false;
		}

		try {
			new Long(value);
		} catch (NumberFormatException e) {
			return false;
		}

		return true;
	}

	/**
	 * Checks if the field can safely be converted to an float primitive.
	 * 
	 * @param value
	 *            String
	 * @return boolean
	 */
	public static boolean validateFloat(String value) {

		if (strIsNull(value)) {
			return false;
		}

		try {
			new Float(value);
		} catch (NumberFormatException e) {
			return false;
		}

		return true;
	}

	/**
	 * Checks if the field is a valid date. If the field has a datePattern
	 * variable.
	 * 
	 * @param value
	 *            String
	 * @param datePattern
	 *            String yyyy-MM-dd HH:mm:ss
	 * @return boolean
	 */
	public static boolean validateDate(String value, String datePattern) {
		if (strIsNull(value)) {
			return false;
		}

		if (datePattern == null || datePattern.length() == 0) {
			datePattern = VssConstants.PATTERN_TIMESTAMP;
		}

		try {
			SimpleDateFormat formatter = Util.getDefaultDateFormat();
			formatter.parse(value);
			if (datePattern.length() != value.length()) {
				return false;
			}
		} catch (ParseException e) {
			return false;
		}

		return true;
	}

	/**
	 * <p>
	 * Checks if the value's length is less than or equal to the max.
	 * </p>
	 * 
	 * @param value
	 *            String
	 * @return boolean
	 */
	public static boolean validateMaxlength(String value, int maxLength) {
		int len = getByteAccount(value, VssConstants.DATABASE_CHARSET);
		return ((len != -1) && (len <= maxLength));
	}

	public static SimpleDateFormat getDefaultDateFormat() {
		SimpleDateFormat df = new SimpleDateFormat(
				VssConstants.PATTERN_TIMESTAMP);
		df.setTimeZone(TimeZone.getTimeZone(VssConstants.DEFAULT_TIMEZONE));
		return df;
	}

	public static int getByteAccount(String str, String charsetName) {
		if (str == null) {
			return 0;
		}
		byte[] bs = null;
		try {
			bs = str.getBytes(charsetName);
		} catch (UnsupportedEncodingException ex) {
			log.warn(str, ex);
			return -1;
		}
		if (bs == null) {
			return -1;
		}
		return bs.length;
	}

	public static String toXmlString(Object obj) {
		String name = obj.getClass().getName();
		if (name.lastIndexOf('$') >= 0) {
			name = name.substring(name.lastIndexOf('$') + 1);
		} else if (name.lastIndexOf('.') >= 0) {
			name = name.substring(name.lastIndexOf('.') + 1);
		}
		String tag = name.substring(0, 1).toLowerCase(Locale.ENGLISH)
				+ name.substring(1);
		return toXmlString(obj, tag);
	}

	private static Element toElement(Object obj, String name) throws Exception {
		if (obj == null) {
			return null;
		}
		Element element = DocumentHelper.createElement(name);
		if (obj instanceof Character || obj instanceof Short
				|| obj instanceof Integer || obj instanceof Boolean
				|| obj instanceof Long || obj instanceof Double
				|| obj instanceof Byte || obj instanceof String
				|| obj.getClass().isPrimitive()) {
			element.setText(String.valueOf(obj));
			return element;
		} else if (obj instanceof Date) {
			element.setText(Util.getDefaultDateFormat().format((Date) obj));
			return element;
		} else if (obj instanceof Map) {
			Map m = (Map) obj;
			Set keys = m.keySet();
			for (Iterator it = keys.iterator(); it.hasNext();) {
				Object key = it.next();
				Object value = m.get(key);
				if (value != null) {
					element.add(toElement(value, key.toString()));
				}
			}
		} else {
			Field[] declaredFields = obj.getClass().getDeclaredFields();
			for (int i = 0; i < declaredFields.length; i++) {
				Field f = declaredFields[i];
				if (Modifier.isFinal(f.getModifiers())
						|| (Modifier.isStatic(f.getModifiers()) || Modifier
								.isTransient(f.getModifiers()))) {
					continue;
				}
				addFieldElement(obj, f, element);
			}
			PropertyDescriptor[] pds = PropertyUtils
					.getPropertyDescriptors(obj);
			for (int i = 0; i < pds.length; i++) {
				String pn = pds[i].getName();
				if (pn.equals("class")
						&& pds[i].getPropertyType().getName().equals(
								"java.lang.Class")) { // getClass();
					continue;
				}
				try {
					obj.getClass().getDeclaredField(pn);
				} catch (Exception ex) {
					Object v = PropertyUtils.getProperty(obj, pn);
					if (v != null) {
						element.add(toElement(v, pn));
					}
				}
			}
		}
		return element;
	}

	private static void addFieldElement(Object obj, Field field,
			Element parentElement) throws Exception {
		field.setAccessible(true);

		Object value = field.get(obj);
		if (value == null) {
			return;
		}
		if (value instanceof List) {
			List list = (List) value;
			parentElement.addComment("<list> size = " + list.size());
			for (int j = 0; j < list.size(); j++) {
				parentElement.add(toElement(list.get(j), field.getName()));
			}
		} else if (value instanceof Set) {
			Set set = (Set) value;
			parentElement.addComment("<set> size = " + set.size());
			for (Iterator it = set.iterator(); it.hasNext();) {
				Object elem = it.next();
				if (elem != null) {
					parentElement.add(toElement(elem, field.getName()));
				}
			}

		} else if (value.getClass().isArray()) {
			int length = Array.getLength(value);
			parentElement.addComment("<array> length = " + length);
			for (int j = 0; j < length; j++) {
				Object item = Array.get(value, j);
				parentElement.add(toElement(item, field.getName()));
			}
		} else {
			parentElement.add(toElement(value, field.getName()));
		}
	}

	public static String toXmlString(Object obj, String name) {
		StringBuffer sb = new StringBuffer();
		String startTag = null;
		String endTag = null;
		if (!Util.strIsNull(name)) {
			startTag = "<" + name + ">";
			endTag = "</" + name + ">";
		}
		if (obj == null) {
			return "<" + name + " />";
		}
		try {
			if (obj instanceof List) {
				if (!Util.strIsNull(name)) {
					sb.append(startTag);
				}
				List list = (List) obj;
				if (log.isDebugEnabled()) {
					sb.append("<!-- <list>  size = ").append(list.size())
							.append(" -->");
				}
				for (Iterator iter = list.iterator(); iter.hasNext();) {
					Object item = iter.next();
					sb.append(toXmlString(item, null));
				}
				if (!Util.strIsNull(name)) {
					sb.append(endTag);
				}
			} else if (obj instanceof Set) {
				if (!Util.strIsNull(name)) {
					sb.append(startTag);
				}
				Set set = (Set) obj;
				if (log.isDebugEnabled()) {
					sb.append("<!-- <set>  size = ").append(set.size()).append(
							" -->");
				}
				for (Iterator iter = set.iterator(); iter.hasNext();) {
					Object item = iter.next();
					if (item != null) {
						sb.append(toXmlString(item, null));
					}
				}
				if (!Util.strIsNull(name)) {
					sb.append(endTag);
				}
			} else if (obj instanceof Map) {
				if (!Util.strIsNull(name)) {
					sb.append(startTag);
				}
				Map map = (Map) obj;
				Set keys = map.keySet();
				for (Iterator iter = keys.iterator(); iter.hasNext();) {
					String key = (String) iter.next();
					Object value = map.get(key);
					if (key != null && value != null) {
						sb.append(toXmlString(value, key));
					}
				}
				if (!Util.strIsNull(name)) {
					sb.append(endTag);
				}
			} else if (obj.getClass().isArray()) {
				if (!Util.strIsNull(name)) {
					sb.append(startTag);
				}
				int length = Array.getLength(obj);
				if (log.isDebugEnabled()) {
					sb.append("<!-- <array>  length = ").append(length).append(
							" -->");
				}
				for (int j = 0; j < length; j++) {
					Object item = Array.get(obj, j);
					if (item != null) {
						sb.append(toXmlString(item, null));
					}
				}
				if (!Util.strIsNull(name)) {
					sb.append(endTag);
				}
			} else {
				if (Util.strIsNull(name)) {
					sb.append(toXmlString(obj));
				} else {
					sb.append(toElement(obj, name).asXML());
				}
			}
		} catch (Exception ex) {
			log.debug(ex);
			return "<" + name + " />";
		}
		return sb.toString();
	}

	public static void copyProperties(Object dest, Object orig) {
		if (dest == null || orig == null) {
			return;
		}
		try {
			PropertyUtils.copyProperties(dest, orig);
		} catch (Throwable ex) {
			log.debug(ex);
		}
		Field[] dfs = dest.getClass().getFields();
		if (dfs == null) {
			return;
		}
		for (int i = 0; i < dfs.length; i++) {
			Field df = dfs[i];
			// if((df.getModifiers()&Field.PUBLIC) == Field.PUBLIC){
			try {
				Field os = orig.getClass().getField(df.getName());
				if ((os.getType() == df.getType())) {
					df.set(dest, os.get(orig));
				}
			} catch (Throwable ex) {
				log.debug(ex);
				try {
					Object value = PropertyUtils
							.getProperty(orig, df.getName());
					df.set(dest, value);
				} catch (Throwable ex1) {
					log.debug(ex1);
				}
			}
		}
	}

	public static String getString(Object obj) {
		if (obj == null || obj.equals("")) {
			return "";
		} else {
			return obj.toString();
		}

	}

	public static void main(String[] args) {

		/**
		 * List list = new ArrayList(); Map map1 = new HashMap(); Map map2 = new
		 * HashMap(); list.add(map1); list.add(map2); map1.put("a", "aa");
		 * map1.put("b", "bb"); map2.put("c", "cc");
		 * 
		 * for (int i = 0; i < 10000; i++) { VideoServer vs = new VideoServer();
		 * map2.put("vs" + i, vs); } long l = System.currentTimeMillis(); //
		 * String s = Util.toXmlString(map2, "dd"); // System.out.println(s);
		 * System.out.println(System.currentTimeMillis() - l);
		 * 
		 * String value = null;
		 * 
		 * int k = Integer.parseInt(value, 10);
		 * 
		 * System.out.println("____k=" + k);
		 */
//		String[] a = new String[] { "1,2", "1,2", "2,3" };
//		String[] b = Util.duplicate(a);
//		for (int i = 0; i < b.length; i++) {
//			System.out.println(b[i]);
//		}
		System.out.println(MD5("12345678"));
	}

	public static Object getObjectFormArr(Object[] arr, int pos) {
		Object value = null;
		try {
			value = arr[pos];
		} catch (Exception e) {
			;
		}
		return value;
	}

	public static String toTrimmedString(Object value) {
		if (value == null) {
			return null;
		}
		return value.toString().trim();
	}

	public static String longDecimalFormat(String pattern, long longValue) {
		String strOfNumber = null;
		try {
			DecimalFormat format = new DecimalFormat(pattern);
			strOfNumber = format.format(longValue);
		} catch (Exception e) {
			strOfNumber = String.valueOf(longValue);
		}
		return strOfNumber;
	}

	public static String doubleDecimalFormat(String pattern, double longValue) {
		String strOfNumber = null;
		try {
			DecimalFormat format = new DecimalFormat(pattern);
			strOfNumber = format.format(longValue);
		} catch (Exception e) {
			strOfNumber = String.valueOf(longValue);
		}
		return strOfNumber;
	}

	public static String floatDecimalFormat(String pattern, float longValue) {
		String strOfNumber = null;
		try {
			DecimalFormat format = new DecimalFormat(pattern);
			strOfNumber = format.format(longValue);
		} catch (Exception e) {
			strOfNumber = String.valueOf(longValue);
		}
		return strOfNumber;
	}

	public static String formatDate(Date myDate, String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		String strDate = formatter.format(myDate);
		return strDate;
	}
	public static String getRoute(HttpServletRequest request){
		String route=getTrimParameter(request, "route");
//		getTrimParameter at least returns "", never null
		String[] url=route.split(",");
		if(url.length<2)return null;
		
		if(CSGConfiguration.patternRoute.matcher(url[1]).matches())
		{
			return url[1];
		
		}else
		{
			throw new VssException(VssConstants.CODE_INVALIDE_ROUTE,new String[]{url[1]});
		}
		
	}
	public static NameValuePair substituteParameter(HttpServletRequest request,String key, String newValue){
		Map map=request.getParameterMap();
		
		if(map.containsKey(key)){
		
		return new NameValuePair(key,newValue);
		}else 
		{
			return null;
		}
	}
	public static String MD5(String input)
	{
		try {
			
		StringBuffer sb=new StringBuffer();
		MessageDigest md=MessageDigest.getInstance("MD5");
		byte maskH=(byte)0xf0;
		byte maskL=(byte)0x0f;
		int d=0x000f;
		byte[] output;
		md.update(input.getBytes());
		MessageDigest md2=(MessageDigest)md.clone();
		output=md2.digest();
		for (int i = 0; i < output.length; i++) 
		{
			sb.append(Integer.toHexString(((byte)((output[i] & maskH)>>4))&d));
			sb.append(Integer.toHexString(((byte)(output[i] & maskL))&d));   
		}
		
		return sb.toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
		
	}
	
}
